package top.ed333.mcplugins.configurableevents.requirement;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import top.ed333.mcplugins.configurableevents.ConsoleSender;

public class PlayerHasItemReqGroup extends TargetedByPlayerEventReqGroup {
    private final ItemStack reqItem;

    public PlayerHasItemReqGroup(String groupName, @NotNull String ext) {
        super(groupName, ext);

        String[] extSpilt = ext.split(",");
        String matName;
        Material reqMat;
        int amt = 1;
        try {
            if (extSpilt.length == 1) {
                matName = ext;
            } else if (extSpilt.length == 2) {
                matName = extSpilt[0];
                amt = Integer.parseInt(extSpilt[1]);
            } else {
                ConsoleSender.warn("错误的条件值: {0}, 位于 条件组 '{1}'", ext, groupName);
                throw new IllegalArgumentException();
            }
            reqMat = Material.valueOf(matName);
        } catch (IllegalArgumentException e) {
            ConsoleSender.warn("错误的条件值: {0}, 位于条件组 '{1}'", ext, groupName);
            throw new RuntimeException(e);
        }
        reqItem = new ItemStack(reqMat, amt);
    }

    @Override
    public boolean checkReq(@NotNull PlayerEvent event) {
        Player player = event.getPlayer();
        Inventory playerInv = player.getInventory();
        return playerInv.contains(reqItem);
    }

    @Override
    public String name() {
        return "PlayerHasItem";
    }
}
